package cn.ulyer.core.secure.authority.strategy;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.ulyer.common.constants.AuthStrategyEnum;
import cn.ulyer.common.security.authority.AuthorityHandlerStrategy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

public class IpHandlerStrategy implements AuthorityHandlerStrategy {


    @Override
    public boolean handler(HttpServletRequest request, Authentication authentication, GrantedAuthority grantedAuthority) {
        String ips = grantedAuthority.getAuthority();
        if (StrUtil.isBlank(ips)) {
            return false;
        }
        String requestIp = ServletUtil.getClientIP(request);
        String[] ipArr = ips.split(",");
        for (String ipRegex : ipArr) {
            if (Pattern.matches(ipRegex, requestIp)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public String strategy() {
        return AuthStrategyEnum.ANY_IP.name();
    }


}
